﻿using System;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace ICodeShare.UI.Converters
{
    [ValueConversion(typeof(CornerRadius), typeof(Thickness))]
    public sealed class CornerRadiusToHalfMarginConverter : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!(value is CornerRadius))
            {
                return DependencyProperty.UnsetValue;
            }

            var source = (CornerRadius)value;

            var parameters = parameter as string;
            if (parameters != null)
            {
                var propertyNames = parameters.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                if (propertyNames.Length > 0)
                {
                    var thickness = new Thickness(0.0);

                    var changed = false;

                    foreach (var propertyName in propertyNames)
                    {
                        switch (propertyName.Trim().ToLower())
                        {
                            case "left":
                                thickness.Left = (source.TopLeft > source.BottomLeft) ? (source.TopLeft / 2) :(source.BottomLeft/2);
                                changed = true;
                                break;
                            case "top":
                                thickness.Top =(source.TopLeft > source.TopRight) ? (source.TopLeft / 2) :(source.TopRight/2); 
                                changed = true;
                                break;
                            case "right":
                                thickness.Right =(source.TopRight > source.BottomRight) ? (source.TopRight / 2) :(source.BottomRight/2);
                                changed = true;
                                break;
                            case "bottom":
                                thickness.Bottom =(source.BottomLeft > source.BottomRight) ? (source.BottomLeft / 2) :(source.BottomRight/2);
                                changed = true;
                                break;
                        }
                    }

                    if (changed)
                    {
                        return thickness;
                    }
                }
            }

            return new Thickness((source.TopLeft + source.BottomLeft) / 4, (source.TopLeft + source.TopRight) / 4, (source.TopRight + source.BottomRight) / 4, (source.BottomLeft + source.BottomRight) / 4);
        }

        object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Contract.Ensures(false);
            throw new NotSupportedException();
        }
    }
}
